// 用户API Mock数据和接口

// 模拟数据生成器
const generateRandomUser = (id) => {
  const firstNames = ['张', '王', '李', '赵', '刘', '陈', '杨', '黄', '周', '吴', '郑', '孙', '马', '朱', '胡']
  const lastNames = ['伟', '芳', '娜', '秀英', '敏', '静', '丽', '强', '磊', '军', '洋', '勇', '艳', '杰', '涛', '明', '超']
  const emailDomains = ['gmail.com', 'yahoo.com', 'hotmail.com', 'outlook.com', 'qq.com', '163.com', '126.com']
  
  const firstName = firstNames[Math.floor(Math.random() * firstNames.length)]
  const lastName = lastNames[Math.floor(Math.random() * lastNames.length)]
  const name = firstName + lastName
  
  // 生成随机手机号
  const phonePrefix = ['138', '139', '137', '136', '135', '134', '159', '158', '157', '188', '187', '186', '151', '150']
  const prefix = phonePrefix[Math.floor(Math.random() * phonePrefix.length)]
  const suffix = Math.floor(Math.random() * 100000000).toString().padStart(8, '0')
  const phone = prefix + suffix
  
  // 生成随机邮箱
  const emailDomain = emailDomains[Math.floor(Math.random() * emailDomains.length)]
  const email = `${phone}@${emailDomain}`
  
  // 生成随机日期
  const now = new Date()
  const threeYearsAgo = new Date(now.getFullYear() - 3, now.getMonth(), now.getDate())
  const createTime = new Date(threeYearsAgo.getTime() + Math.random() * (now.getTime() - threeYearsAgo.getTime()))
  const updateTime = new Date(createTime.getTime() + Math.random() * (now.getTime() - createTime.getTime()))
  
  return {
    id: id || Date.now(),
    name,
    phone,
    email,
    create_at: createTime.toLocaleString('zh-CN', { hour12: false }),
    update_time: updateTime.toLocaleString('zh-CN', { hour12: false })
  }
}

// 模拟数据库
let mockUsers = []
for (let i = 1; i <= 50; i++) {
  mockUsers.push(generateRandomUser(i))
}

// 模拟网络延迟
const delay = (ms = 300) => new Promise(resolve => setTimeout(resolve, ms))

// 用户API接口
export const userApi = {
  // 获取用户列表
  async list(params = {}) {
    await delay()
    
    try {
      const { page = 1, size = 10, keyword = '' } = params
      
      // 搜索过滤
      let filteredUsers = mockUsers
      if (keyword) {
        filteredUsers = mockUsers.filter(user => 
          user.name.includes(keyword) || 
          user.phone.includes(keyword) || 
          user.email.includes(keyword)
        )
      }
      
      // 分页
      const total = filteredUsers.length
      const start = (page - 1) * size
      const end = start + size
      const data = filteredUsers.slice(start, end)
      
      return {
        list: data,
        total,
        page,
        size
      }
    } catch (error) {
      return {
        code: 500,
        message: '获取用户列表失败',
        data: null
      }
    }
  },

  // 添加用户
  async add(userData) {
    await delay()
    
    try {
      // 验证必填字段
      if (!userData.name || !userData.phone || !userData.email) {
        return {
          code: 400,
          message: '姓名、手机号和邮箱为必填项',
          data: null
        }
      }
      
      // 检查手机号是否已存在
      const existingUser = mockUsers.find(user => user.phone === userData.phone)
      if (existingUser) {
        return {
          code: 400,
          message: '手机号已存在',
          data: null
        }
      }
      
      // 生成新用户
      const newUser = {
        id: Math.max(...mockUsers.map(u => u.id)) + 1,
        name: userData.name,
        phone: userData.phone,
        email: userData.email,
        create_at: new Date().toLocaleString('zh-CN', { hour12: false }),
        update_time: new Date().toLocaleString('zh-CN', { hour12: false })
      }
      
      mockUsers.unshift(newUser)
      
      return {
        code: 200,
        message: '添加成功',
        data: newUser
      }
    } catch (error) {
      return {
        code: 500,
        message: '添加用户失败',
        data: null
      }
    }
  },

  // 编辑用户
  async edit(userData) {
    await delay()
    const id = userData.id
    try {
      const userIndex = mockUsers.findIndex(user => user.id === id)
      if (userIndex === -1) {
        return {
          code: 404,
          message: '用户不存在',
          data: null
        }
      }
      
      // 验证必填字段
      if (!userData.name || !userData.phone || !userData.email) {
        return {
          code: 400,
          message: '姓名、手机号和邮箱为必填项',
          data: null
        }
      }
      
      // 检查手机号是否被其他用户使用
      const existingUser = mockUsers.find(user => user.phone === userData.phone && user.id !== id)
      if (existingUser) {
        return {
          code: 400,
          message: '手机号已被其他用户使用',
          data: null
        }
      }
      
      // 更新用户信息
      const updatedUser = {
        ...mockUsers[userIndex],
        name: userData.name,
        phone: userData.phone,
        email: userData.email,
        update_time: new Date().toLocaleString('zh-CN', { hour12: false })
      }
      
      mockUsers[userIndex] = updatedUser

      return {
        code: 200,
        message: '更新成功',
        data: updatedUser
      }
    } catch (error) {
      return {
        code: 500,
        message: '更新用户失败',
        data: null
      }
    }
  },

  // 批量删除用户
  async delete(ids) {
    await delay()
    
    try {
      const deletedUsers = []
      const notFoundIds = []
      
      ids.forEach(id => {
        const userIndex = mockUsers.findIndex(user => user.id === id)
        if (userIndex !== -1) {
          deletedUsers.push(mockUsers.splice(userIndex, 1)[0])
        } else {
          notFoundIds.push(id)
        }
      })
      
      if (notFoundIds.length > 0) {
        return {
          code: 400,
          message: `部分用户不存在: ${notFoundIds.join(', ')}`,
          data: { deletedUsers, notFoundIds }
        }
      }
      
      return {
        code: 200,
        message: `成功删除 ${deletedUsers.length} 个用户`,
        data: deletedUsers
      }
    } catch (error) {
      return {
        code: 500,
        message: '批量删除用户失败',
        data: null
      }
    }
  },

  // 获取单个用户详情
  async getById(id) {
    await delay()
    
    try {
      const user = mockUsers.find(user => user.id === id)
      if (!user) {
        return {
          code: 404,
          message: '用户不存在',
          data: null
        }
      }
      
      return {
        code: 200,
        message: '获取成功',
        data: user
      }
    } catch (error) {
      return {
        code: 500,
        message: '获取用户详情失败',
        data: null
      }
    }
  }
}

// 导出默认接口
export default userApi